﻿namespace TypeCounter
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Timers;
    using System.Windows;

    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public InputCounter InputCounter { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="App"/> class.
        /// </summary>
        public App()
        {
            // Input counter setup
            this.InputCounter = new InputCounter();
            this.LoadCounters();

            // Auto save timer
            var timer = new Timer();
            timer.Interval = TypeCounter.Properties.Settings.Default.AutoSaveTimeSpan.TotalMilliseconds;
            timer.Elapsed += OnTimerElapsed;
            timer.Start();

            // Show main window
            var mainWindow = new MainWindow();
            mainWindow.Closing += OnMainWindowClosing;
            mainWindow.Show();
        }

        /// <summary>
        /// Called when timer elapsed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="elapsedEventArgs">The <see cref="ElapsedEventArgs"/> instance containing the event data.</param>
        private void OnTimerElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
        {
            this.SaveCounters();
        }

        /// <summary>
        /// Called when main window is closing.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="cancelEventArgs">The <see cref="CancelEventArgs"/> instance containing the event data.</param>
        private void OnMainWindowClosing(object sender, CancelEventArgs cancelEventArgs)
        {
            this.SaveCounters();
        }

        /// <summary>
        /// Saves the counters.
        /// </summary>
        private void SaveCounters()
        {
            TypeCounter.Properties.Settings.Default.KeyboardPressCount = this.InputCounter.KeyboardPressCount;
            TypeCounter.Properties.Settings.Default.MouseClickCount = this.InputCounter.MouseClickCount;
            TypeCounter.Properties.Settings.Default.Save();
        }

        /// <summary>
        /// Loads the counters.
        /// </summary>
        private void LoadCounters()
        {
            this.InputCounter.KeyboardPressCount = TypeCounter.Properties.Settings.Default.KeyboardPressCount;
            this.InputCounter.MouseClickCount = TypeCounter.Properties.Settings.Default.MouseClickCount;
        }
    }
}
